package com.csmy.my.center.util.servlet;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.csmy.my.center.module.CustomerInfo;
import com.csmy.my.center.util.AttachMentMethod;
import com.csmy.my.center.util.CTUtils;
import com.csmy.my.center.util.RequestUtil;
import com.csmy.my.center.util.StringUtil;
import com.csmy.my.center.util.dataconvert.Dto;
import com.csmy.my.center.util.dataconvert.impl.BaseDto;
import com.csmy.my.center.util.db.JdbcTemplateTool;
import com.csmy.my.center.util.report.excel.JxlsUtil;

public class ExportCustOrderServlet extends HttpServlet {

	private static final long serialVersionUID = 4765424700702151344L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		try {
			//获取待发货的订单
			Dto paramDto = new BaseDto();
			String reqPath = req.getRequestURI();
			String nowURl = req.getServletPath();
			Dto dto =  RequestUtil.getPraramsAsDto(req);
			CustomerInfo customerInfo = RequestUtil.getCUser(req);
			String temp_path = nowURl.substring(nowURl.lastIndexOf("/") + 1, nowURl.length());
			
			String state_id = getParamFromURl(reqPath, temp_path);
			paramDto.put("pageSize", "1000000");
			paramDto.put("state_id",state_id);
			paramDto.put("customer_id",customerInfo.getCustomer_id());
			//处理订单
			String order_id = dto.getAsString("order_id");
			String tempID = dto.getAsString("tempid");//模板id
			if(CTUtils.isNotEmpty(order_id)){
				order_id = order_id.replaceAll(",", "','");
				paramDto.put("order_id", order_id);
			}
			List<Dto> orderList = JdbcTemplateTool.getCTOrderList(paramDto).getDatas();
			if(CTUtils.isNotEmpty(orderList)){
				//处理总金额
				double totalMoney =0L; 
				for (Dto dto2 : orderList) {
					
					String city = dto2.getAsString("city");
					String area = dto2.getAsString("area");
					String address = dto2.getAsString("address");
					String sku_name = dto2.getAsString("sku_name");
					String good_name = dto2.getAsString("good_name");
					String province = dto2.getAsString("province");
					
					double price = Double.valueOf(dto2.getAsString("sku_price"));
					int buy_num = dto2.getAsInteger("buy_num");
					double tprice = price*buy_num;
					totalMoney+=tprice;
					dto2.put("tprice", tprice);
					dto2.put("userAddr",province+city+area+" "+address);//拼接地址
					dto2.put("goodStr", good_name+"/"+ sku_name);
					
					//处理订单状态
					String order_state = dto2.getAsString("state");
					dto2.put("state_name", CTUtils.getCodeName("ORDER_STATE", order_state));
				}
				
				String templateFile = JxlsUtil.class.getClassLoader().getResource("").getPath(); 
				//处理导出全部的情况
				String tempFile=null;
				String outTempFile = null;
				if(CTUtils.isEmpty(state_id)||tempID.equals("1")){
					tempFile=templateFile+"template/newOrderTemplate.xls";
					outTempFile = templateFile+"template/"+CTUtils.getCurDateNoSplit()+"_simple_outfile.xls";
					StringUtil.xprint("导出全部订单信息...");
				}else{
					tempFile=templateFile+"template/orderTemplate.xls";
					outTempFile = templateFile+"template/"+CTUtils.getCurDateNoSplit()+"_cod_outfile.xls";
					StringUtil.xprint("导出待发货订单信息...");
				}
				OutputStream os=new FileOutputStream(outTempFile);
		        
		        Map<String, Object> beans=new HashMap<String, Object>(); 
		        beans.put("orderList", orderList);
		        beans.put("count", orderList.size());
		        beans.put("totalMoney", totalMoney);
				boolean temp = JxlsUtil.export2Excel(beans, tempFile, os);
				if(temp){
					AttachMentMethod attchMethod = new AttachMentMethod();
					attchMethod.downloadFile(outTempFile);
				}else{
					RequestUtil.renderHtml("<script>alert('很抱歉，导出数据失败！');window.history.back(-1);</script>");
				}
			}else{
				RequestUtil.renderHtml("<script>alert('很抱歉，没有待导出的订单！');window.history.back(-1);</script>");
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	/**
	 * 获取参数
	 * @param url
	 * @return
	 */
	public static String getParamFromURl(String url,String surl) {
		String param=null;
		if(StringUtil.isNotEmpty(url)){
			String tempUrl = url.substring(url.lastIndexOf(surl), url.length());
			String params[] = tempUrl.split("\\/");
			if(params.length==3){
			   param = params[2];
			}
			if(params.length==2){
			   param = params[1];
			}
		}
		StringUtil.xprint("state_id="+param);
		return param;
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}

}
